package com.atguigu.utils;

import com.alibaba.druid.pool.DruidPooledConnection;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.bean.TableProcess;
import com.google.common.base.CaseFormat;
import org.apache.commons.beanutils.BeanUtils;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * select count(*) from t;                          单行单列
 * select count(*) from t group by dept_name;       单行多列
 * select * from t where id = 'xxx'; id为主键        多行单列
 * select * from t;                                 多行多列
 */
public class JdbcUtil {

    public static <T> List<T> queryList(Connection connection, String sql, Class<T> clz, boolean underScoreToCamel) throws Exception {

        //创建集合用于存放结果
        ArrayList<T> list = new ArrayList<>();

        //编译SQL
        PreparedStatement preparedStatement = connection.prepareStatement(sql);

        //执行查询操作
        ResultSet resultSet = preparedStatement.executeQuery();
        ResultSetMetaData metaData = resultSet.getMetaData();
        int columnCount = metaData.getColumnCount();

        //遍历resultSet,将每行数据封装为T对象
        while (resultSet.next()) {

            //创建T对象
            T t = clz.newInstance();

            //列遍历,将每个列设置进T对象
            for (int i = 1; i < columnCount + 1; i++) {
                String columnName = metaData.getColumnName(i);
                Object value = resultSet.getObject(columnName);

                if (underScoreToCamel) {
                    columnName = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, columnName.toLowerCase());
                }

                //将列名与列值放入T对象
                BeanUtils.setProperty(t, columnName, value);
            }

            list.add(t);
        }

        //释放资源
        resultSet.close();
        preparedStatement.close();

        //返回集合
        return list;
    }

    public static void main(String[] args) throws Exception {

//        DruidPooledConnection connection = DruidDSUtil.getPhoenixConn();

        Connection connection = DriverManager.getConnection("jdbc:mysql://hadoop103:3306/gmall-221109-config?" +
                "user=root&password=000000&useUnicode=true&" +
                "characterEncoding=utf8&serverTimeZone=Asia/Shanghai&useSSL=false");

        List<TableProcess> queryList = queryList(connection,
                "select  * from table_process",
                TableProcess.class,
                true);

        for (TableProcess jsonObject : queryList) {
            System.out.println(jsonObject);
        }

        connection.close();

    }

}
